package com.specificgroup.jira.plugin.acpro.action;

import com.specificgroup.jira.plugin.acpro.service.JiraAcproPluginJiraManager;

/**
 *
 * @author Ivan Holub
 */
public class AcproItemNumberCustomFieldAction extends AcproActionSupport {

    private static final String NEXT_ACTION = "AcproUserMapping!default.jspa";

    private JiraAcproPluginJiraManager jiraAcproPluginJiraManager;

    private boolean acproItemNumberCustomFieldExists;

    public boolean isAcproItemNumberCustomFieldExists() {
        return acproItemNumberCustomFieldExists;
    }

    public AcproItemNumberCustomFieldAction(JiraAcproPluginJiraManager jiraAcproPluginJiraManager) {
        this.jiraAcproPluginJiraManager = jiraAcproPluginJiraManager;
    }

    @Override
    public String doDefault() throws Exception {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }

        acproItemNumberCustomFieldExists = jiraAcproPluginJiraManager.isAcproItemNumberCustomFieldExists();

        return super.doDefault();
    }

    @Override
    protected String doExecute() throws Exception {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }
        
        String redirect = getRedirect(NEXT_ACTION);
        return redirect;
    }

    public String doCreateCustomField() {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }

        jiraAcproPluginJiraManager.createAcproItemNumberCustomField();

        return SUCCESS;
    }

    @Override
    protected void doValidation() {

        acproItemNumberCustomFieldExists = jiraAcproPluginJiraManager.isAcproItemNumberCustomFieldExists();

        if (!acproItemNumberCustomFieldExists) {
            addErrorMessage(getText("error.notexist"));
        }

        super.doValidation();
    }
}
